package com.sky.aspect;

import com.sky.annotation.DelRedisDish;
import com.sky.enumeration.RedisCategoryType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

@Aspect
@Component
@Slf4j
public class DelTRedisDishAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 切入点
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.DelRedisDish)")
    public void DelRedisDishPointCut() {
    }

    @Before("DelRedisDishPointCut()")
    public void delRedisDish(JoinPoint joinPoint) {
        log.info("开始进行填充");

        //2.获取拦截的参数
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {

            //1.获取方法上数据库操作的类型
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            DelRedisDish annotation = signature.getMethod().getAnnotation(DelRedisDish.class);
            RedisCategoryType value = annotation.value();
            String redisKey = "";
            // 根据 RedisCategoryType 进行不同的 Redis 操作
            switch (value) {
                case SETMEAL:
                    redisKey = "setmeal_*";

                    break;
                case SETMEALDISH:
                    redisKey = "setmealdish_*";

                    break;
                case DISH:
                    redisKey = "dish_*";

                    break;
            }
            // 删除 Redis 中的缓存数据
            Set keys = redisTemplate.keys(redisKey);
            redisTemplate.delete(keys);

        }


    }
}
